package com.wb.mas.ui.login;

import android.app.Application;
import android.text.TextUtils;

import com.appsflyer.AFInAppEventParameterName;
import com.appsflyer.AppsFlyerLib;
import com.blankj.utilcode.util.SPUtils;
import com.wb.mas.R;
import com.wb.mas.app.SPKeys;
import com.wb.mas.data.DemoRepository;
import com.wb.mas.entity.IdentityInfoResponse;
import com.wb.mas.entity.LoginResponse;
import com.wb.mas.entity.RootApiBean;
import com.wb.mas.ui.base.viewmodel.ToolbarViewModel;
import com.wb.mas.ui.main.MainViewModel;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class LoginByPhoneViewModel2 extends ToolbarViewModel {
    public LoginByPhoneViewModel2(@NonNull Application application, DemoRepository model) {
        super(application, model);
    }

    private String phoneNum;


    public void setPhoneNum(String phone_num) {
        this.phoneNum = phone_num;
    }

    public UiChangeEvent ui = new UiChangeEvent();

    public class UiChangeEvent {
        public SingleLiveEvent<String> loginSucEvent = new SingleLiveEvent<>();

    }

    public ObservableField<String> inputContent = new ObservableField<>("");
    public ObservableField<String> smsTitleHint = new ObservableField<>("");
    public ObservableField<String> acquireSmsCode = new ObservableField<>(getString(R.string.login_by_phone_acquire_code));
    public ObservableField<Boolean> isCommitEnable = new ObservableField<>(true);
    public ObservableField<Boolean> isSmsClickAble = new ObservableField<>(true);

    public BindingCommand onClickNextStep = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            String inputContent = LoginByPhoneViewModel2.this.inputContent.get();
            if (!TextUtils.isEmpty(inputContent)) {

                loginWithPhoneAndSmdCode();

            } else {
                ToastUtils.showShort(getString(R.string.auth_pi_please_input_hint));
            }
        }
    });

    private void loginWithPhoneAndSmdCode() {
        showDialog();
        Map<String, Object> params = new HashMap<>();
        params.put("mobile", phoneNum);
        params.put("verificationCode", LoginByPhoneViewModel2.this.inputContent.get());
        model.loginByPhoneCode(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<LoginResponse>() {
                    @Override
                    public void accept(LoginResponse infoResponse) throws Exception {
                        dismissDialog();
                        if (infoResponse != null && infoResponse.getStatus() == 200 && infoResponse.getData() != null && !TextUtils.isEmpty(infoResponse.getData().getToken())) {


                            String token = infoResponse.getData().getToken();
                            SPUtils.getInstance().put(SPKeys.KEY_OF_TOKEN, token);
                            Messenger.getDefault().send("", MainViewModel.AUTH_SUC_EVENT);

                            ui.loginSucEvent.setValue("");
                            KLog.i("login with phone suc,token:" + infoResponse.getData().getToken());


                            trackLoginEvent(infoResponse);

                        } else {
                            ToastUtils.showShort(infoResponse.getMessage());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        ToastUtils.showShort(throwable.getMessage());
                    }
                });
    }

    private void trackLoginEvent(LoginResponse infoResponse) {
        if ("1".equalsIgnoreCase(infoResponse.getData().getUserType())) {
            //appflyers的埋点
            Map<String, Object> eventValue = new HashMap<>();
            eventValue.put("userId", infoResponse.getData().getId());
            AppsFlyerLib.getInstance().trackEvent(getApplication(),
                    "mobileLogin", eventValue);
        } else {
            //新用户注册
            Map<String, Object> eventValue = new HashMap<>();
            eventValue.put("userId", infoResponse.getData().getId());
            AppsFlyerLib.getInstance().trackEvent(getApplication(),
                    "mobileRegister", eventValue);
        }
    }

    public BindingCommand onClickGetSmsCode = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            acquireSmsCodeData();


        }
    });

    private void acquireSmsCodeData() {
        showDialog();
        Map<String, Object> params = new HashMap<>();
        params.put("mobile", phoneNum);
        model.getSmsCode(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<RootApiBean>() {
                    @Override
                    public void accept(RootApiBean infoResponse) throws Exception {
                        dismissDialog();
                        if (infoResponse != null && infoResponse.getStatus() == 200) {
                            CountDown();
                        } else {
                            ToastUtils.showShort(infoResponse.getMessage());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        ToastUtils.showShort(throwable.getMessage());
                    }
                });
    }

    private void CountDown() {
        final int count = 60;//倒计时10秒
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return count - aLong;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())//ui线程中进行控件更新
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        isSmsClickAble.set(false);
                    }
                }).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long num) {

                acquireSmsCode.set(num + "s");
//                            button.setText("剩余" + num + "秒");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                //回复原来初始状态
                acquireSmsCode.set(getString(R.string.login_by_phone_acquire_code));
                isSmsClickAble.set(true);
            }
        });
    }


    @Override
    public void onCreate() {
        super.onCreate();

        CountDown();

        smsTitleHint.set(getString(R.string.login_by_phone_send_sms_prefix) + phoneNum);

    }
}
